package ink.ykb.actDemo.taskListener;

import java.util.List;

import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.el.FixedValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ink.ykb.actDemo.dao.LeaveDao;
import ink.ykb.actDemo.dao.UserInfoDao;
import ink.ykb.actDemo.entity.Leave;
import ink.ykb.actDemo.entity.UserInfo;
import ink.ykb.actDemo.util.HttpRequestLocal;
import ink.ykb.actDemo.util.PlatformRuntimeException;
import ink.ykb.actDemo.util.bean.PostType;

/**
 * 审批时动态注入审批人Assignee
 * @author dell
 *
 */
@Service
public class LeaveReviewTaskListener implements TaskListener{

	private static final long serialVersionUID = 854152376962374708L;
	@Autowired
	private HttpRequestLocal httpRequestLocal;
	@Autowired
	private UserInfoDao userInfoDao;
	@Autowired
	private LeaveDao leaveDao;
	
	private FixedValue post;

	@Override
	public void notify(DelegateTask delegateTask) {
		//TODO 如果是员工请假，他的下一个审批人应该是当前部门的项目经理
		//如果是项目经理请假，他就应该跳过项目经理审批
		//如果是老板请假，他能跳过项目经理和老板审批
		
		Integer leaveId = (Integer)delegateTask.getVariable("leaveId");
		if(post != null && leaveId != null) {
			Leave leave = leaveDao.single(leaveId);
			Integer postValue = Integer.valueOf(post.getValue(delegateTask).toString());
			Integer uId = null; 
			if(postValue == PostType.EMP.getId()) {
				uId = leave.getUid();
			}else if(postValue == PostType.BM.getId() || postValue == PostType.BOSS.getId()) {
				List<UserInfo> list = userInfoDao.createLambdaQuery().andEq(UserInfo::getPost, postValue).select();
				if(list != null && list.size() >0) {
					uId = list.get(0).getId();
				}
			}
			if(uId == null) {
				throw new PlatformRuntimeException("Assignee 不能为 null");
			}
			delegateTask.setAssignee(uId.toString());
		}
		
	}

	public void setPost(FixedValue fixedValue) {
		this.post = fixedValue;
	}
	
}
